package com.newtouch.bxzs.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.em.CustomerTagEnum;
import com.newtouch.bxzs.common.base.model.EnterpriseCustomer;
import com.newtouch.bxzs.common.base.model.EnterpriseCustomerGroupMap;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.PinYinUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.enterprise.mapper.EnterpriseCustomerGroupMapMapper;
import com.newtouch.bxzs.enterprise.mapper.EnterpriseCustomerMapper;
import com.newtouch.bxzs.enterprise.model.bo.EnterpriseCustomerBO;
import com.newtouch.bxzs.enterprise.model.bo.EnterpriseCustomerDetailBO;
import com.newtouch.bxzs.enterprise.model.vo.EnterpriseCustomerDetailVO;
import com.newtouch.bxzs.enterprise.model.vo.EnterpriseCustomerVO;
import com.newtouch.bxzs.enterprise.service.EnterpriseCustomerService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业客户serviceImpl
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/2/3 9:44</td>
 * <td>dingqianbin</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author dingqianbin
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class EnterpriseCustomerServiceImpl implements EnterpriseCustomerService {

    @Autowired
    private EnterpriseCustomerMapper enterpriseCustomerMapper;

    @Autowired
    private EnterpriseCustomerGroupMapMapper enterpriseCustomerGroupMapMapper;

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(EnterpriseCustomerServiceImpl.class);

    @Override
    public EnterpriseCustomerBO getCustomerList(EnterpriseCustomerVO enterpriseCustomerVO) {
        EnterpriseCustomerBO enterpriseCustomerBO = new EnterpriseCustomerBO();
        List<EnterpriseCustomer> enterpriseCustomerList = enterpriseCustomerMapper.getCustomerList(StringUtils.isEmpty(enterpriseCustomerVO.getEnterpriseCustomerName()) ? null : enterpriseCustomerVO.getEnterpriseCustomerName(), StringUtils.isEmpty(enterpriseCustomerVO.getEnterpriseCustomerGroupId()) ? null : enterpriseCustomerVO.getEnterpriseCustomerGroupId(), Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserJobNumber());
        /*当查询集合为空时 */
        if(CollectionUtils.isEmpty(enterpriseCustomerList)) {
            /*返回空集 */
            enterpriseCustomerBO.setList(Collections.emptyList());
            enterpriseCustomerBO.setCount(0);
            return enterpriseCustomerBO;
        }
        enterpriseCustomerBO.setList(EntityToBeanUtils.copyBean(enterpriseCustomerList, EnterpriseCustomerDetailBO.class));
        enterpriseCustomerBO.setCount(enterpriseCustomerList.size());
        return enterpriseCustomerBO;
    }

    @Override
    public EnterpriseCustomerDetailBO getEnterpriseCustomerDetail(String enterpriseCustomerId) {
        if (StringUtils.isEmpty(enterpriseCustomerId)) {
            logger.error("根据企业客户ID获取企业客户详情请求参数为空!");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*根据企业客户ID获取当前企业客户详情 */
        EnterpriseCustomer enterpriseCustomer = enterpriseCustomerMapper.selectById(enterpriseCustomerId);
        if (BeanUtil.isEmpty(enterpriseCustomer)) {
            return null;
        }
        EnterpriseCustomerDetailBO enterpriseCustomerDetailBO = new EnterpriseCustomerDetailBO();
        BeanUtils.copyProperties(enterpriseCustomer, enterpriseCustomerDetailBO);
        /*根据企业客户ID获取该企业客户与分组的对应关系*/
        List<EnterpriseCustomerGroupMap> enterpriseCustomerGroupMapList = enterpriseCustomerGroupMapMapper.selectList(new QueryWrapper<EnterpriseCustomerGroupMap>().eq("ENTERPRISE_CUSTOMER_ID", enterpriseCustomerDetailBO.getEnterpriseCustomerId()));
        /*遍历该企业客户与分组的对应关系等到对应的企业客户分组ID集合*/
        List<String> groupsList = new ArrayList<>();
        for (EnterpriseCustomerGroupMap enterpriseCustomerGroupMap : enterpriseCustomerGroupMapList) {
            groupsList.add(enterpriseCustomerGroupMap.getEnterpriseCustomerGroupId());
        }
        /*返回企业客户分组ID集合*/
        enterpriseCustomerDetailBO.setEnterpriseCustomerGroupIds(groupsList);
        return enterpriseCustomerDetailBO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer modifyEnterpriseCustomer(EnterpriseCustomerDetailVO enterpriseCustomerDetailVO) {
        /*校验必填项*/
        if (StringUtils.isEmpty(enterpriseCustomerDetailVO.getEnterpriseCustomerName())
                || StringUtils.isEmpty(enterpriseCustomerDetailVO.getEnterpriseCustomerLinkmanName())
                || StringUtils.isEmpty(enterpriseCustomerDetailVO.getEnterpriseCustomerLinkmanPhone())
                || StringUtils.isEmpty(enterpriseCustomerDetailVO.getUnifiedSocialCreditCode())) {
            logger.error("必填项未填写！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        /*校验手机号格式*/
        if (!StringUtils.isEmpty(enterpriseCustomerDetailVO.getEnterpriseCustomerLinkmanPhone())
                && !Validator.isMobile(enterpriseCustomerDetailVO.getEnterpriseCustomerLinkmanPhone())) {
            logger.error("手机号格式不正确，请重新输入");
            throw new BaseException("-1","手机号格式不正确，请重新输入");
        }
        EnterpriseCustomer enterpriseCustomer = new EnterpriseCustomer();
        BeanUtils.copyProperties(enterpriseCustomerDetailVO, enterpriseCustomer);
        Date date = new Date();
        String userId = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId();
        /*客户标签 --> 自建客户*/
        enterpriseCustomer.setCustomerLabel(CustomerTagEnum.SELF_BUILT.getCode());//客户标签: 1,存 2,建 3,分 4,接
        enterpriseCustomer.setEnterpriseCustomerNameFullSpelling(PinYinUtils.toFirstChar(enterpriseCustomer.getEnterpriseCustomerName()).replaceAll("[^a-z^A-Z]", ""));
        enterpriseCustomer.setUpdateUserId(userId);
        enterpriseCustomer.setUpdateTime(date);
        /*判断企业客户ID是否为空，为空则新增企业客户，不为空则修改企业客户信息*/
        if (StringUtils.isEmpty(enterpriseCustomer.getEnterpriseCustomerId())) {
            enterpriseCustomer.setCreateUserId(userId);
            enterpriseCustomer.setUserJobNumber(UserDetailUtil.getUserDetail().getUserJobNumber());
            enterpriseCustomer.setCreateTime(date);
            /*插入企业客户信息*/
            if (enterpriseCustomerMapper.insertEnterpriseCustomer(enterpriseCustomer) !=1 ) {
                logger.error("新增企业客户信息失败，存在相同的企业客户名称或者统一社会信用代码");
                throw new BaseException(BaseErrorEnum.DATA_EXISTS);
            }
        } else {
            /*获取当前企业客户的详细信息*/
            EnterpriseCustomer customer = enterpriseCustomerMapper.selectById(enterpriseCustomer.getEnterpriseCustomerId());
            if (BeanUtil.isEmpty(customer)) {
                logger.error("该企业客户ID未查询到对应的企业客户信息，请求参数错误！");
                throw new BaseException(BaseErrorEnum.REQUEST_PARAMETER_ERROR);
            }
            /*获取该企业客户的标签集合(客户标签: 1,存 2,建 3,分 4,接)*/
            List<String> labelList = Arrays.asList(customer.getCustomerLabel().split(","));
            /*只有自建客户才允许被修改*/
            if (labelList.contains(CustomerTagEnum.SELF_BUILT.getCode())) {
                /*自建客户成为存量的企业客户企业名称，统一社会信用代码不可修改*/
                if (labelList.contains(CustomerTagEnum.STOCK.getCode())) {
                    if (!enterpriseCustomer.getEnterpriseCustomerName().equals(customer.getEnterpriseCustomerName())) {
                        logger.info("自建客户成为存量的企业客户企业名称不可修改！");
                        throw new BaseException(BaseErrorEnum.FIELD_CANNOT_MODIFY);
                    }
                    if (!StringUtils.isEmpty(customer.getUnifiedSocialCreditCode()) && !enterpriseCustomer.getUnifiedSocialCreditCode().equals(customer.getUnifiedSocialCreditCode())) {
                        logger.info("自建客户成为存量的企业客户统一社会信用代码不可修改！");
                        throw new BaseException(BaseErrorEnum.FIELD_CANNOT_MODIFY);
                    }
                }
                String enterpriseCustomerName = null;
                String unifiedSocialCreditCode = null;
                /*如果对企业客户名称有修改，验证修改后的企业客户名称是否存在相应企业客户，若存在修改失败*/
                if (!enterpriseCustomer.getEnterpriseCustomerName().equals(customer.getEnterpriseCustomerName())) {
                    enterpriseCustomerName = enterpriseCustomer.getEnterpriseCustomerName();
                }
                /*如果对统一社会信用代码有修改，验证修改后的统一社会信用代码是否存在相应企业客户，若存在修改失败*/
                if (!enterpriseCustomer.getUnifiedSocialCreditCode().equals(customer.getUnifiedSocialCreditCode())) {
                    unifiedSocialCreditCode = enterpriseCustomer.getUnifiedSocialCreditCode();
                }
                if (enterpriseCustomerMapper.updateEnterpriseCustomer(enterpriseCustomer, enterpriseCustomerName, unifiedSocialCreditCode) != 1) {
                    logger.error("修改企业客户信息失败，存在相同的企业客户名称或者统一社会信用代码");
                    throw new BaseException(BaseErrorEnum.DATA_EXISTS);
                }
            }
        }
        /*将企业客户批量插入分组*/
        return this.insertBatchGroupMap(enterpriseCustomerDetailVO.getEnterpriseCustomerGroupIds(),enterpriseCustomer.getEnterpriseCustomerId());
    }

    /**
     * 操作企业客户的分组信息
     *
     * @param enterpriseCustomerGroupIds 企业客户分组ID集合
     * @param enterpriseCustomerId 企业客户ID
     */
    private Integer insertBatchGroupMap(List<String> enterpriseCustomerGroupIds, String enterpriseCustomerId) {
        /*将企业客户所有企业分组对应关系删除*/
        enterpriseCustomerGroupMapMapper.delete(new QueryWrapper<EnterpriseCustomerGroupMap>().eq("ENTERPRISE_CUSTOMER_ID", enterpriseCustomerId));
        if (!CollectionUtils.isEmpty(enterpriseCustomerGroupIds)) {
            Date date = new Date();
            String userId = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId();
            /*批量将企业客户添加到对应的企业分组中*/
            List<EnterpriseCustomerGroupMap> enterpriseCustomerGroupMapList = new ArrayList<>();
            for (String enterpriseCustomerGroupId : enterpriseCustomerGroupIds) {
                EnterpriseCustomerGroupMap item = new EnterpriseCustomerGroupMap();
                item.setEnterpriseCustomerGroupId(enterpriseCustomerGroupId);
                item.setEnterpriseCustomerId(enterpriseCustomerId);
                item.setCreateUserId(userId);
                item.setCreateTime(date);
                item.setUpdateUserId(userId);
                item.setUpdateTime(date);
                enterpriseCustomerGroupMapList.add(item);
            }
            return enterpriseCustomerGroupMapMapper.insertBatch(enterpriseCustomerGroupMapList);
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteEnterpriseCustomer(List<EnterpriseCustomerDetailVO> enterpriseCustomerDetailVOList) {
        /*判断企业客户ID集合是否为空*/
        if (CollectionUtils.isEmpty(enterpriseCustomerDetailVOList)) {
            logger.error("删除/批量删除企业客户信息请求参数为空！");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        int listSize = enterpriseCustomerDetailVOList.size();
        /*只有自建未成为存量企业客户才允许删除，将不属于自建未成为存量的企业客户信息移除*/
        enterpriseCustomerDetailVOList.removeIf(enterpriseCustomerDetailVO->!(enterpriseCustomerDetailVO.getCustomerLabel().contains(CustomerTagEnum.SELF_BUILT.getCode()) && !enterpriseCustomerDetailVO.getCustomerLabel().contains(CustomerTagEnum.STOCK.getCode())));
        List<String> enterpriseCustomerIds = enterpriseCustomerDetailVOList.stream().map(EnterpriseCustomerDetailVO::getEnterpriseCustomerId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(enterpriseCustomerDetailVOList) && enterpriseCustomerDetailVOList.size() == listSize && !CollectionUtils.isEmpty(enterpriseCustomerIds)){
            /*删除企业客户信息后再删除企业客户与分组对应关系表*/
            if (enterpriseCustomerMapper.deleteBatchIds(enterpriseCustomerIds) > 0) {
                /*删除该企业客户与分组对应关系*/
                return enterpriseCustomerGroupMapMapper.delete(new QueryWrapper<EnterpriseCustomerGroupMap>().in("ENTERPRISE_CUSTOMER_ID", enterpriseCustomerIds));
            }
        }else{
            logger.error("只能删除自建未成为存量企业客户信息！");
            throw new BaseException(BaseErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        return null;
    }


}
